package com.ease.context.encrypt;

public class BinHex {

	final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public String encrypt(String value) {
		if (null == value || "".equals(value)) {
			throw new IllegalArgumentException("value is empty");
		}
		char[] input = value.toCharArray();
		int length = input.length;
		char[] output = new char[length];
		for (int i = 0; i < length; i++) {
			char c = value.charAt(i);
			int displacement = 0;
			if (c >= '0' && c <= '9') {
				displacement = c - '0';
			} else if (c >= 'A' && c <= 'F') {
				displacement = c - 'A' + 10;
			} else {
				throw new IllegalArgumentException("value contains invalid char");
			}
			displacement = ((displacement + i) % 16);
			output[i] = HEX[displacement];
		}
		return new String(output);
	}

	public String decrypt(String value) {
		if (null == value || "".equals(value)) {
			throw new IllegalArgumentException("value is empty");
		}

		char[] input = value.toCharArray();
		int length = input.length;
		char[] output = new char[length];
		for (int i = 0; i < length; i++) {
			char c = value.charAt(i);
			int displacement = 0;
			if (c >= '0' && c <= '9') {
				displacement = c - '0';
			} else if (c >= 'A' && c <= 'F') {
				displacement = c - 'A' + 10;
			} else {
				throw new IllegalArgumentException("value contains invalid char");
			}
			displacement = (displacement - i) % 16;
			if (displacement < 0) {
				displacement += 16;
			}
			output[i] = HEX[displacement];
		}
		return new String(output);
	}
}
